package utils;

import cn.hutool.crypto.digest.MD5;
import com.ksc.cdn.KscCdnClient;
import com.ksc.cdn.KscCdnContent;
import com.ksc.cdn.model.content.RefreshCachesRequest;
import com.ksc.cdn.model.content.RefreshCachesResult;
import com.ksc.cdn.model.content.Url;
import com.ksc.util.Md5Utils;
import org.junit.Assert;
import org.springframework.util.DigestUtils;

public class KsyunUtils {

    private static final String KS_DOMAIN = "hw.ahtv.cn";
    private static final String AUTH_KEY = "Abc12345";

    public static void main(String[] args) throws Exception {
        System.out.println("generateAuthUrl = " +
                generateAuthUrl("http://dbxz1-hw.ahtv.cn/ahtv-transcoding/20210127/ed5d001e-4384-ab55-3a1d-65d1dd010090_H.264_544x960_HEAAC_882.mp4"));

        String md5_spring = DigestUtils.md5DigestAsHex("哈哈哈".getBytes());
        String md5_hutool = MD5.create().digestHex("哈哈哈".getBytes());
        String md5_ksyun = Md5Utils.md5AsBase64("哈哈哈".getBytes());
        System.out.println("md5_spring = " + md5_spring);
        System.out.println("md5_hutool = " + md5_hutool);
        System.out.println("md5_ksyun = " + md5_ksyun);
    }

    /**
     * 生成时间戳+共享密钥防盗链
     *
     * @param url
     * @return
     */
    public static String generateAuthUrl(String url) {
        String[] fileName = url.split(KS_DOMAIN);
        if (fileName.length > 1) {
            long timeStamp = System.currentTimeMillis() / 1000;
            String encryptStr = AUTH_KEY + fileName[1] + timeStamp;
            //对密码进行 md5 加密
            String md5Hash = DigestUtils.md5DigestAsHex(encryptStr.getBytes());
            return url + "?t=" + timeStamp + "&k=" + md5Hash;
        } else {
            return url;
        }
    }

    private static void refreshCDNCache() throws Exception {
        String aws_access_key_id = "AKLTcSHIxm7GSiKG9J_QOpZ44g";
        String aws_secret_access_key = "OL1LuTNhjilYKzjzRHtz9MEGJXFQn2W8iGqjfztY/bRnKw/IQtXsoVdo6silH6MXSA==";

        KscCdnContent client = new KscCdnClient(aws_access_key_id,
                aws_secret_access_key,
                "http://cdn.api.ksyun.com",
                "cn-shanghai-1",
                "cdn");
        Url[] files = new Url[1];
        files[0] = new Url("http://dbxz1-hw.ahtv.cn/ahtv-obs/20201030/5d8aa2f9-6771-7469-4e4a-3ef533e7cf38.png");
        RefreshCachesRequest refreshCachesRequest = new RefreshCachesRequest();
        refreshCachesRequest.setFiles(files);
        RefreshCachesResult result = client.refreshCaches(refreshCachesRequest);
        System.out.println("result = " + result.getRefreshTaskId());
        Assert.assertNotNull(result.getRefreshTaskId());
    }
}
